import { Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { Config } from '@midwayjs/decorator';
import { Repository } from 'typeorm';
// import dayjs from 'dayjs';
import { BaseService } from '@core/index';
import { RegisterDTO, LoginDTO, UserUpdateDTO } from '@dto/user';
import { UserEntity } from '@entity/user';
import { FriendEntity } from '@entity/friend';

@Provide()
export class UserService extends BaseService {
  @InjectEntityModel(UserEntity)
  userEntity: Repository<UserEntity>;

  @InjectEntityModel(FriendEntity)
  friendEntity: Repository<FriendEntity>;

  @Config('koa')
  configKoa;

  @Config('jwt')
  configJwt;

  /**
   * 注册
   * @param register
   */
  async register(register: RegisterDTO) {
    console.log('register', register);
    const user = await this.userEntity.findOne({
      where: { email: register.email },
    });

    if (user && user.email) {
      return this.success(200, '该账户已注册');
    }
    const params = {
      ...register,
      imgUrl: `http://${this.configKoa.host}:${this.configKoa.port}/public/images/qq.png`,
    };
    await this.userEntity.save(params);
    return this.success(200, '注册成功');
  }

  /**
   * 登陆
   * @param login
   */
  async login(login: LoginDTO) {
    const user = await this.userEntity.findOne({
      where: { email: login.email },
    });
    if (user) {
      if (user.password === login.password) {
        // const token = await this.tokenUtil.generateToken(user);
        const token = await this.tokenUtil.generateToken(user);
        return this.success(200, '登陆成功', token);
      }
      return this.success(200, '用户名或密码不正确');
    }
    return this.success(200, '用户不存在');
  }

  /**
   * 获取用户信息
   * @param getUser
   */
  async getUser() {
    const userToken: any = await this.tokenUtil.verifyToken();
    // console.log('userToken', userToken);
    const user = await this.userEntity.findOne({
      where: { id: Number(userToken.payload.userId) },
      select: [
        'id',
        'username',
        'account',
        'email',
        'sex',
        'birth',
        'phone',
        'desc',
        'imgUrl',
        'createTime',
        'updateTime',
      ],
    });
    return this.success(200, '获取成功', user);
  }

  /**
   * 获取用户列表信息
   * @param getUserList
   */
  async getUserList() {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = userToken.payload.userId;
    const user = await this.userEntity.find({
      select: [
        'id',
        'username',
        'account',
        'email',
        'sex',
        'birth',
        'phone',
        'desc',
        'imgUrl',
        'createTime',
        'updateTime',
      ],
      order: {
        id: 'DESC',
      },
    });

    const data = await this.friendEntity.find({
      where: [{ userId }, { friendId: userId }],
    });
    const ids = data.map(item => {
      if (item.friendId === userId) {
        return Number(item.userId);
      }
      return Number(item.friendId);
    });

    const formatUser = user.map(item => {
      const idsRes = ids.find((value: number) => value === Number(item.id));
      if (idsRes && idsRes === Number(item.id)) {
        item.status = 0;
      } else if (item.id === userToken.payload.userId) {
        item.status = 0;
      } else {
        item.status = 1;
      }
      return item;
    });

    return this.success(200, '获取成功', formatUser);
  }

  /**
   * 修改用户信息
   * @param updateUser
   */
  async updateUser(params: UserUpdateDTO) {
    const { username, account, email, sex, birth, phone, desc, imgUrl } =
      params;
    const userToken: any = await this.tokenUtil.verifyToken();
    const users = await this.userEntity.findOne({
      where: {
        id: userToken.payload.userId,
      },
    });
    if (users) {
      const result = await this.userEntity
        .createQueryBuilder()
        .update()
        .set({
          username: username || users.username,
          account: account || users.account,
          email: email || users.email,
          sex: sex || users.sex,
          birth: birth || users.birth,
          phone: phone || users.phone,
          desc: desc || users.desc,
          imgUrl: imgUrl || users.imgUrl,
        })
        .where({ id: userToken.payload.userId })
        .execute();
      return this.success(200, '修改成功', result);
    }
    return this.success(500, '出错了');
  }
}
